import Vue from 'vue'
import Vuex from 'vuex'

import {getSchoolTree} from '@/api/user.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 数据仓库
  state: {
    history: [], // 搜索历史记录
		userInfo:{},
		hasLogin: false,
		schoolData: [],
		// baseTarget: 'http://192.168.3.72:9999'
		// baseTarget: 'http://192.168.3.67:9999',
		// baseTarget: 'http://47.111.3.41:9999',
		baseTarget: 'https://www.xymsdp.top'
  },
  mutations: {
    setHistory(state, history) {
      state.history = history
    },
    clearHistory(state, history) {
      state.history = history
    },
	login(state, userInfo) {
		state.hasLogin = true;
		state.userInfo = userInfo;
	},
	logout(state) {
		state.hasLogin = false
	},
	setSchoolData(state, data){
		state.schoolData = data
	}
  },

  actions: {
    setHistory({commit, state}, history) {
      let list = state.history
      list.unshift(history)
      commit('setHistory', list)
    },
    clearHistory({commit, state}, history) {
      commit('setHistory', [])
    },
	setSchoolData({commit, state}){
		return new Promise((resolve, reject)=>{
			const data = uni.getStorageSync('schoolData')
			if(state.schoolData.length === 0){
				if(data){ 
					commit('setSchoolData', data)
					resolve(data)
				}else{ // 缓存中也没有schoolData
					getSchoolTree().then(res=>{
						if(res.code === 200){
							commit('setSchoolData', res.data)
							uni.setStorageSync('schoolData', res.data)
							resolve(res.data)
							// this.schoolData = res.data
						}else{
							resolve([])
							uni.showToast({title: res.message})
						}
					})
				}
			}else{
				resolve(state.schoolData)
			}
		})
	},
  }
})

export default store